package com.lovo.Stream;

import java.io.*;

public class SerializeUtil {
    /**
     * 序列化对象
     *
     * @param path 保存序列化对象路径
     * @param obj  序列化对象
     */
    public static void writeObject(String path, Object obj) {
        FileOutputStream fos = null;
        ObjectOutputStream oos = null;//转为二进制
        try {
            fos = new FileOutputStream(path);
            oos = new ObjectOutputStream(fos);//流链接
            oos.writeObject(obj);//选择对象进行序列化
            oos.flush();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fos != null) {
                try {
                    oos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    /**
     * 反序列化对象
     *
     * @param path 保存反序列化对象路径
     * @return
     */
    public static Object readObject(String path) {
        FileInputStream fis = null;
        ObjectInputStream ois = null;
        try {
            fis = new FileInputStream(path);
            ois = new ObjectInputStream(fis);
            return (Object) ois.readObject();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;//出现异常了就会返回空值
    }


}
